let express = require('express');
let router = express.Router();
let fs = require('fs');
let path = require('path');


/* GET home page. */
router.get('/', function (req, res, next) {
  res.render('index', {title: 'Express'});
});

/* GET home page. */
router.get('/list', function (req, res, next) {
  // 数据库  从数据库中获取
  // mysql select * from list

  let list = fs.readFileSync(path.join(__dirname, '../data/list.json'), 'utf-8');
  // console.log(path.join(__dirname, 'data/list.json'));
  res.send(list);
});

/* GET home page. */
router.post('/delete', function (req, res, next) {
  // 数据库  从数据库中获取
  // mysql select * from list

  let list = fs.readFileSync(path.join(__dirname, '../data/list.json'), 'utf-8');
  let {id} = req.body;
  list = JSON.parse(list);
  let newList = list.filter(item => !(item.id === Number(id)));
  fs.writeFileSync(path.join(__dirname, '../data/list.json'), JSON.stringify(newList), 'utf-8');

  res.send({
    code: 1,
    message: '删除成功'
  });
});

/* GET home page. */
router.post('/edit', function (req, res, next) {
  let list = fs.readFileSync(path.join(__dirname, '../data/list.json'), 'utf-8');
  list = JSON.parse(list);
  let {id, name, age} = req.body;
  let newList = [];
  list.forEach(item => {
    if (item.id === id) {
      item['name'] = name;
      item['age'] = age;
    }
    newList.push(item);
  });

  fs.writeFileSync(path.join(__dirname, '../data/list.json'), JSON.stringify(newList), 'utf-8');

  res.send({
    code: 1,
    message: '编辑成功'
  });
});

/* GET home page. */
router.post('/add', function (req, res, next) {
  let list = fs.readFileSync(path.join(__dirname, '../data/list.json'), 'utf-8');
  list = JSON.parse(list);
  let {name, age} = req.body;
  //id : 取出最后一条数据 +1
  let id = list[list.length - 1]['id'] + 1;
  list.push({id, name, age});
  fs.writeFileSync(path.join(__dirname, '../data/list.json'), JSON.stringify(list), 'utf-8');
  res.send({
    code: 1,
    message: '添加成功'
  });
});


module.exports = router;
